package com.ticket.sass.admin.controller;


import com.alibaba.excel.EasyExcel;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.ticket.sass.admin.annotation.AuthIgnore;
import com.ticket.sass.admin.business.CouponCodeBusiness;
import com.ticket.sass.admin.business.FileUpLoadBusiness;
import com.ticket.sass.admin.dto.input.coupons.code.CouponCodeBatchListInput;
import com.ticket.sass.admin.dto.input.coupons.code.CouponCodeListInput;
import com.ticket.sass.admin.dto.input.coupons.code.CouponGenerateInput;
import com.ticket.sass.admin.dto.output.coupons.code.CouponCodeBatchListOutput;
import com.ticket.sass.admin.dto.output.coupons.code.CouponCodeExportDTO;
import com.ticket.sass.admin.dto.output.coupons.code.CouponCodeListOutput;
import com.ticket.sass.admin.handler.IdentityInput;
import com.ticket.sass.admin.manager.ThreadLocalIdInputHolderManager;
import com.ticket.sass.admin.model.PageModel;
import com.ticket.sass.admin.model.ResultModel;
import com.ticket.sass.common.exception.enums.ErrorCode;
import com.ticket.sass.common.exception.exception.BadRequestException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 优惠券表 前端控制器
 * </p>
 *
 * @author ywb
 * @since 2024-03-13
 */
@RestController
@AllArgsConstructor
@Api(tags = {"优惠券-兑换码-模块"})
@ApiSupport(order = 9)
@RequestMapping("/coupons/{id}/codes")
public class CouponCodeController {
    final CouponCodeBusiness business;
    final FileUpLoadBusiness fileUpLoadBusiness;
    
    @ApiOperation("列表")
    @GetMapping
    public ResultModel<PageModel<CouponCodeListOutput>> list(
        @PathVariable Long id,
        @Valid CouponCodeListInput input
  
    ) {
        return ResultModel.success(
            business.list(id, input)
        );
    }
    
    @ApiOperation("批次号列表")
    @GetMapping("/batches")
    public ResultModel<PageModel<CouponCodeBatchListOutput>> batchList(
        @PathVariable Long id,
        @Valid CouponCodeBatchListInput input
    
    ) {
        return ResultModel.success(
            business.batchList(id, input)
        );
    }
    
    @ApiOperation("生成")
    @PostMapping("/generate")
    public ResultModel<String> generate(
        @PathVariable Long id,
        @Valid CouponGenerateInput input
    
    ) {
        business.generate(id, input);
        return ResultModel.success();
    }
    
    @AuthIgnore
    @ApiOperation("导出")
    @GetMapping("/export")
    public void exportCouponCodes(
        @PathVariable Long id,
        @Valid CouponCodeListInput input,
        HttpServletResponse response,
        @Valid Long cinemaId,
        @Valid String token
    ) throws IOException {
        if (Objects.isNull(cinemaId)){
            throw new BadRequestException(
                ErrorCode.BUSINESS_ERROR,
                "影院ID不能为空"
            );
        }
        if (!fileUpLoadBusiness.existExportToken(token, "coupon-code")) {
            throw new BadRequestException(
                ErrorCode.BUSINESS_ERROR,
                "token过期"
            );
        }
        
        // 设置请求参数
        input.setPageNum(1);
        input.setPageSize(1000);
        
        IdentityInput value = ThreadLocalIdInputHolderManager.getValue();
        value.setCinemaId(cinemaId);
        
        ThreadLocalIdInputHolderManager.setValue(value);
        
        // 调用业务逻辑获取数据
        List<CouponCodeListOutput> list = business.list(id, input).getList();
        
        // 转换数据为导出所需的DTO格式
        List<CouponCodeExportDTO> exportData = list.stream()
            .map(entity -> {
                return new CouponCodeExportDTO(entity.getBatchNum(), entity.getCode());
            })
            .collect(Collectors.toList());
        
        // 设置响应头
        // 设置响应头，指定Content-Type和文件名
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode(System.currentTimeMillis() + "", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
        // 写入数据到Excel文件
        try (OutputStream outputStream = response.getOutputStream()) {
            EasyExcel.write(outputStream, CouponCodeExportDTO.class).sheet("兑换码").doWrite(exportData);
        } catch (Exception e) {
            // 处理异常
            e.printStackTrace();
            throw new BadRequestException(
                ErrorCode.BUSINESS_ERROR,
                "导出失败"
            );
        }
    }
}
